from django.http import JsonResponse

from django.shortcuts import get_object_or_404

from web.models import CloudShop_Goods, CloudShop_User, CloudShop_Order

from django import forms

from web import Success_Error_Dict

from django.forms.models import model_to_dict

from django.core.mail import EmailMessage

from django.conf import settings

import time

import os


class CloudShop_Goods_Form(forms.ModelForm):
    class Meta:
        model = CloudShop_Goods
        fields = '__all__'


# 商品添加
def CloudShop_Goods_Add(request):
    if request.method == 'POST':
        new_data = request.POST.copy()
        new_data['status'] = 1
        new_data['user'] = CloudShop_User.objects.filter(id = new_data['user']).first()
        form = CloudShop_Goods_Form(data = new_data, files = request.FILES)
        if form.is_valid():
            # 获取文件大小
            file_size = request.FILES['goods_file'].size
            if file_size > 1024 * 1024 * 10:
                response = Success_Error_Dict.Error_Dict
                response['msg'] = '文件大小不能超过10M'
                return JsonResponse(response, status = 400, content_type = 'application/json')
            saved_instance = form.save()
            response = Success_Error_Dict.Success_Dict
            response['msg'] = '添加成功'
            response['data'] = form.cleaned_data
            response['data']['goods_main_img'] = "/media/" + str(saved_instance.goods_main_img)
            response['data']['goods_file'] = "/media/" + str(saved_instance.goods_file)
            response['data']['user'] = model_to_dict(response['data']['user'])

            # 删除敏感数据
            del response['data']['goods_file']
            del response['data']['user']['user_password']
            del response['data']['user']['user_email']
            return JsonResponse(response, status = 200, content_type = 'application/json')
        else:
            response = Success_Error_Dict.Error_Dict
            response['msg'] = '添加失败'
            return JsonResponse(response, status = 400, content_type = 'application/json')
    else:
        response = Success_Error_Dict.Request_Error_Dict
        return JsonResponse(response, status = 400, content_type = 'application/json')


# 查询商品
def CloudShop_Goods_Query(request):
    # 全局变量, 方便对数据进行操作, 避免重复代码
    global Goods_All
    global start
    global end

    if request.method == 'GET':
        response = {"code": 0, "msg": "Success", "data": None, "total": None}
        search_type = request.GET.get('type', '1')  # 查询类型
        page = request.GET.get('page', '1')
        if page == "1":
            start = 0
            end = int(page) * 20
        else:
            start = (int(page) - 1) * 20
            end = int(page) * 20
        if search_type == '1':
            Goods_All = [model_to_dict(obj) for obj in CloudShop_Goods.objects.filter(status = 1).order_by('-id')]
        elif search_type == '2':
            # 根据goods_id查询
            goods_id = request.GET.get('goods_id')
            if goods_id is None:
                response = Success_Error_Dict.Param_Error_Dict
                response['msg'] = '请提供goods_id值'
                return JsonResponse(response, status = 400, content_type = 'application/json')
            Goods_All = [model_to_dict(obj) for obj in
                         CloudShop_Goods.objects.filter(id = goods_id, status = 1).order_by('-id')]
            if len(Goods_All) == 0:
                response = Success_Error_Dict.Param_Error_Dict
                response['msg'] = '请提供正确的goods_id值'
                return JsonResponse(response, status = 400, content_type = 'application/json')

        # 假设总数居有100条, 每一页显示20条数据, 总共有多少页
        total_page = int(len(Goods_All) / 20) + 1
        # 对数据进行操作
        Goods_All = Goods_All[start:end]
        for obj in Goods_All:
            # 由于默认的图片路径是相对路径，所以需要加上/media/
            obj['goods_main_img'] = '/media/' + str(obj['goods_main_img'])
            obj['user'] = model_to_dict(CloudShop_User.objects.filter(id = obj['user']).first())
            # 删除用户的一些敏感数据
            del obj['user']['user_password']
            del obj['user']['user_email']
            del obj['goods_file']

        if search_type != '2':
            response['total'] = total_page
            response['data'] = Goods_All
        else:
            # 查询单个商品时不需要列表
            response['data'] = Goods_All[0]
            del response['total']
        return JsonResponse(response, status = 200, content_type = 'application/json')
    else:
        response = Success_Error_Dict.Request_Error_Dict
        return JsonResponse(response, status = 400, content_type = 'application/json')


# 购买商品
def buy_goods(request):
    if request.method == 'POST':
        response = Success_Error_Dict.Request_Error_Dict

        goods_id = request.POST.get('goods_id')
        user_id = request.POST.get('user_id')
        if goods_id is None or user_id is None:
            response['msg'] = '请提供goods_id和user_id'
            return JsonResponse(response, status = 400, content_type = 'application/json')

        goods = CloudShop_Goods.objects.filter(id = goods_id).first()
        user_info = CloudShop_User.objects.filter(id = user_id).first()
        if goods is None:
            response['msg'] = '商品不存在'
            return JsonResponse(response, status = 400, content_type = 'application/json')
        if user_info is None:
            response['msg'] = '用户不存在'
            return JsonResponse(response, status = 400, content_type = 'application/json')
        if goods.user.id == user_id:
            response['msg'] = '不能购买自己的商品'
            return JsonResponse(response, status = 400, content_type = 'application/json')
        if goods.status == 2:
            response['msg'] = '商品已下架'
            return JsonResponse(response, status = 400, content_type = 'application/json')
        if user_info.money < goods.price:
            response['msg'] = '余额不足'
            return JsonResponse(response, status = 400, content_type = 'application/json')

        # 购买商品并减去余额
        user_info.money -= goods.price
        user_info.save()
        # 把商品改为已下架
        goods.status = 2
        goods.save()

        # 新增数据到订单表中
        CloudShop_Order.objects.create(
            order_id = str(time.time()).replace('.', ''),
            goods = goods,
            user = CloudShop_User.objects.filter(id = goods.user.id).first(),
            buy_user = user_info,
            order_price = goods.price,
            order_status = 1
        )
        response['msg'] = '购买成功, 当商家发货后我们会通过邮箱方式通知您'
        response['code'] = 200
        return JsonResponse(response, status = 200, content_type = 'application/json')
    else:
        response = Success_Error_Dict.Request_Error_Dict
        return JsonResponse(response, status = 400, content_type = 'application/json')


# 我的订单
def my_order(request):
    if request.method == 'POST':
        def a(gs):
            a_list = []
            for o in gs:
                go = {
                    "order_id": o.order_id,
                    "goods_name": o.goods.name,
                    "order_price": o.order_price,
                    "order_status": o.get_order_status_display(),
                    "buy_user_name": o.buy_user.user_name,
                    "buy_user_email": o.buy_user.user_email,
                    "order_time": o.order_time.strftime("%Y年%m月%d日 %H时:%I分:%S秒")
                }
                a_list.append(go)
            return a_list
        response = {"code": -1, "msg": "Success", "data": None, "count": None}
        show_type = request.POST.get("show_type", "1")  # 查询类型
        user_id = request.POST.get("user_id")
        if user_id is None:
            response['msg'] = "请提供用户id"
            return JsonResponse(response, status = 400, content_type = 'application/json')
        else:
            # 查询用户
            user_info = CloudShop_User.objects.filter(id=user_id).first()
            if user_info is None:
                response['msg'] = "用户不存在"
                return JsonResponse(response, status=400, content_type='application/json')
            else:
                data_all = []
                # 用户存在
                if show_type == '1' or show_type == '2':
                    # 查询待发货商品(商家)
                    goods_list = CloudShop_Order.objects.filter(user=user_info, order_status=show_type).order_by('-id')
                    data_all.append(a(gs=goods_list))
                elif show_type == '3':
                    # 查询交易成功
                    goods_user_list = a(CloudShop_Order.objects.filter(user=user_info, order_status=show_type))
                    goods_buy_user_list = a(CloudShop_Order.objects.filter(buy_user=user_info, order_status=show_type))
                    if len(goods_buy_user_list) > 0:
                        for obj in goods_buy_user_list:
                            goods_user_list.append(obj)

                    data_all.append(goods_user_list)
                elif show_type == '4':
                    # 查询交易成功
                    goods_user_list = a(CloudShop_Order.objects.filter(user=user_info, order_status=show_type)).order_by('-id')
                    goods_buy_user_list = a(CloudShop_Order.objects.filter(buy_user=user_info, order_status=show_type)).order_by('-id')
                    if len(goods_buy_user_list) > 0:
                        for obj in goods_buy_user_list:
                            goods_user_list.append(obj)

                    data_all.append(goods_user_list)
                elif show_type == '5':
                    goods_user_list = CloudShop_Order.objects.filter(buy_user=user_info, order_status=2).order_by('-id')
                    data_all.append(a(gs=goods_user_list))
                elif show_type == '6':
                    goods_user_list = CloudShop_Goods.objects.filter(user=user_info).order_by('-id')
                    for o in goods_user_list:
                        go = {
                            "order_id": o.id,
                            "goods_name": o.name,
                            "order_price": o.price,
                            "order_status": o.get_status_display(),
                        }
                        data_all.append(go)
                    response['code'] = 0
                    response['data'] = data_all
                    return JsonResponse(response, status=200, content_type='application/json')
                elif show_type == '7':
                    goods_list = CloudShop_Order.objects.filter(buy_user=user_info, order_status=1).order_by('-id')
                    for obj in goods_list:
                        go = {
                            "order_id": obj.order_id,
                            "goods_name": obj.goods.name,
                            "order_price": obj.order_price,
                            "order_status": obj.get_order_status_display(),
                            "buy_user_name": obj.user.user_name,
                            "buy_user_email": obj.user.user_email,
                            "order_time":obj.order_time.strftime("%Y年%m月")
                        }
                        data_all.append(go)
                    response['code'] = 0
                    response['data'] = data_all
                    return JsonResponse(response, status = 200, content_type = 'application/json')
                response['code'] = 0
                if len(data_all) > 0:
                    response['data'] = data_all[0]
                else:
                    response['data'] = []
                return JsonResponse(response, status = 200, content_type = 'application/json')
    else:
        response = Success_Error_Dict.Request_Error_Dict
        return JsonResponse(response, status = 400, content_type = 'application/json')


# 退款
def refund(request):
    if request.method == 'POST':
        order_id = request.POST.get('order_id')
        if order_id is None:
            response = Success_Error_Dict.Param_Error_Dict
            response['msg'] = '请提供退款id'
            return JsonResponse(response, status = 400, content_type = 'application/json')
        else:
            order_info = CloudShop_Order.objects.filter(order_id = order_id).first()
            if order_info is None:
                response = Success_Error_Dict.Param_Error_Dict
                response['msg'] = '订单不存在'
                return JsonResponse(response, status = 400, content_type = 'application/json')
            elif order_info.order_status == 4:
                response = Success_Error_Dict.Param_Error_Dict
                response['msg'] = '订单已被退款'
                return JsonResponse(response, status = 400, content_type = 'application/json')
            else:
                # 找到用户并把价格还给他
                user_info = CloudShop_User.objects.filter(id = order_info.buy_user.id).first()
                user_info.money += order_info.order_price
                user_info.save()

                # 发送退款成功邮箱给客户
                # 创建邮件
                email = EmailMessage(
                     f'退款提醒: {order_info.goods.name}退款成功',
                     '退款成功，退款金额：' + str(order_info.order_price) + '元, 已返回到您的账号, 希望下次能为你提供更好的体验',
                    settings.EMAIL_HOST_USER,
                    [order_info.buy_user.user_email],
                )

                email.send()

                # 把订单状态改为已退款
                order_info.order_status = 4
                order_info.save()
                response = Success_Error_Dict.Success_Dict
                response['msg'] = '退款成功'
                response['code'] = 200
                response['data'] = None
                return JsonResponse(response, status = 200, content_type = 'application/json')
    else:
        response = Success_Error_Dict.Request_Error_Dict
        return JsonResponse(response, status = 400, content_type = 'application/json')


# 发货
def deliver(request):
    if request.method == 'POST':
        order_id = request.POST.get('order_id')
        if order_id is None:
            response = Success_Error_Dict.Error_Dict
            response['msg'] = '请提供订单id'
            return JsonResponse(response, status = 400, content_type = 'application/json')
        else:
            order_info = CloudShop_Order.objects.filter(order_id = order_id).first()
            if order_info is None:
                response = Success_Error_Dict.Error_Dict
                response['msg'] = '订单不存在'
                return JsonResponse(response, status = 400, content_type = 'application/json')
            elif order_info.order_status == 2:
                response = Success_Error_Dict.Error_Dict
                response['msg'] = '订单已发货'
                return JsonResponse(response, status = 400, content_type = 'application/json')
            elif order_info.order_status == 3:
                response = Success_Error_Dict.Error_Dict
                response['msg'] = '订单已验收'
                return JsonResponse(response, status = 400, content_type = 'application/json')
            elif order_info.order_status == 1:
                # 判断文件大小
                if order_info.goods.goods_file.size > 1024 * 1024 * 10:
                    response = Success_Error_Dict.Error_Dict
                    response['msg'] = '文件大小超过10M'
                    return JsonResponse(response, status = 400, content_type = 'application/json')

                # 创建邮件
                email = EmailMessage(
                    f"商品{order_info.goods.name}已发货",
                    '尊敬的用户，您的订单已发货，当确认无误后请验收',
                    settings.EMAIL_HOST_USER,
                    [order_info.buy_user.user_email],
                )

                # 添加附件
                email.attach_file(order_info.goods.goods_file.path)

                # 发送邮件
                email.send()

                order_info.order_status = 2
                order_info.save()
                response = Success_Error_Dict.Success_Dict
                response['msg'] = '发货成功'
                response['code'] = 200
                response['data'] = None
                return JsonResponse(response, status = 200, content_type = 'application/json')
            elif order_info.order_status == 4:
                response = Success_Error_Dict.Error_Dict
                response['msg'] = '订单已退款'
                return JsonResponse(response, status = 400, content_type = 'application/json')
            else:
                response = Success_Error_Dict.Error_Dict
                response['msg'] = '订单状态错误'
                return JsonResponse(response, status = 400, content_type = 'application/json')
    else:
        response = Success_Error_Dict.Request_Error_Dict
        return JsonResponse(response, status = 400, content_type = 'application/json')


# 确认收货
def accept(request):
    if request.method == 'POST':
        order_id = request.POST.get('order_id')
        if order_id is None:
            response = Success_Error_Dict.Error_Dict
            response['msg'] = '请提供订单id'
            return JsonResponse(response, status = 400, content_type = 'application/json')
        else:
            order_info = CloudShop_Order.objects.filter(order_id = order_id).first()
            if order_info is None:
                response = Success_Error_Dict.Error_Dict
                response['msg'] = '订单不存在'
                return JsonResponse(response, status = 400, content_type = 'application/json')
            elif order_info.order_status != 2:
                response = Success_Error_Dict.Error_Dict
                response['msg'] = '订单状态错误'
                return JsonResponse(response, status = 400, content_type = 'application/json')
            else:
                # 创建邮件
                email = EmailMessage(
                    f"商品{order_info.goods.name}已验收",
                    '尊敬的用户，您的订单已验收，感谢您的使用',
                    settings.EMAIL_HOST_USER,
                    [order_info.buy_user.user_email],
                )
                email.send()
                order_info.order_status = 3
                order_info.save()

                user_info = CloudShop_User.objects.filter(id = order_info.user.id).first()
                user_info.money += order_info.order_price
                user_info.save()
                response = Success_Error_Dict.Success_Dict
                response['msg'] = '验收成功'
                response['code'] = 200
                response['data'] = None
                return JsonResponse(response, status = 200, content_type = 'application/json')
    else:
        response = Success_Error_Dict.Request_Error_Dict
        return JsonResponse(response, status = 400, content_type = 'application/json')
